<!-- 保养标准 -->
<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">标准</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">保养标准</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form1" label-position="right" label-width="100px" :rules="rules.rules1" :model="formData.data">
							<el-form-item label="标准编号：">
								<el-input v-model="formData.data.maintenanceCode" placeholder=" " :maxlength="curTextareaLength" :disabled="true" />
							</el-form-item>
							<el-form-item label="标准名称：" prop="maintenanceName">
								<el-input v-model="formData.data.maintenanceName" :maxlength="curTextareaLength" :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="说明：">
								<el-input v-model="formData.data.remark" :maxlength="curTextareaLength" show-word-limit type="textarea" :autosize="{ minRows: 2 }" :disabled="isReadOnly" />
							</el-form-item>
						</el-form>
					</div>
					<EffectAndFailureTime ref="effectTimeRef" title="生效状态" id="sm-drawer-demo-card-03" :isReadOnly="isReadOnly" labelWidth="110px" />
					<CreateUserInfo v-if="formData.data.id" ref="createDataRef" title="创建信息" id="sm-drawer-demo-card-04" />
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import EffectAndFailureTime from '@/components/effectAndFailureTime.vue';
	import CreateUserInfo from '@/components/createUserInfo.vue';
	import { standardMaintainAddApi, standardMaintainUpdateApi, standardMaintainInfoApi } from '@/api/equipment.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';

	const route = useRoute();

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);
	const curTextareaLength = ref(store.state.uiTextareaLength);

	const emit = defineEmits(['close']);

	let isShowDrawer = ref(props.isShow);

	let formData = reactive({ data: {} });

	const rules = reactive({
		rules1: {
			maintenanceName: [{ required: true, message: '请填写标准名称', trigger: ['blur', 'change'] }],
		},
	});

	const curNodeList = ref([
		{ name: '保养标准', id: 'sm-drawer-demo-card-01' },
		{ name: '生效状态', id: 'sm-drawer-demo-card-03' },
	]);

	const form1 = ref();
	const forms = [form1];
	const effectTimeRef = ref();
	const createDataRef = ref();

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && props.handleType == 'add' && initForm();
				newVal && ['info', 'edit'].includes(props.handleType) && getInfo(props.currentRow?.id);
			});
		},
	);

	//详情
	const getInfo = async id => {
		let res = await standardMaintainInfoApi({ id });
		if (res.data.code !== 200) return;
		let existCreate = curNodeList.value.find(item => item.id === 'sm-drawer-demo-card-04');
		!existCreate && curNodeList.value.push({ name: '创建信息', id: 'sm-drawer-demo-card-04' });
		formData.data = Object.assign(res.data.data);
		effectTimeRef.value.setTime({ effectTime: formData.data.startTime, expireTime: formData.data.endTime });
		nextTick(() => {
			createDataRef.value.setData(formData.data);
		});
	};

	//提交
	const doConfirm = async () => {
		const validatePromises = forms.map(form => new Promise(resolve => form.value.validate(resolve)));
		const timeModel = effectTimeRef.value.checkRequired();
		validatePromises.push(timeModel);

		Promise.all(validatePromises).then(async results => {
			const isValid = results.every(valid => valid);
			if (!isValid) return;
			delete formData.data.maintenanceCode;
			let params = Object.assign(formData.data, effectTimeRef.value.getFiled());
			params.pointId = route.query.pointId;
			let res = formData.data.id ? await standardMaintainUpdateApi(params) : await standardMaintainAddApi(params);
			if (res.data.code == 200) {
				ElMessage({
					message: '提交成功',
					type: 'success',
				});
				isShowDrawer.value = false;
				emit('close', { isShow: false, isRefresh: true });
			}
		});
	};

	//关闭抽屉
	const handleClose = done => {
		effectTimeRef.value.restTime();
		emit('close', { isShow: false });
		done();
	};

	//表单初始化
	const initForm = () => {
		formData.data = {};

		effectTimeRef.value.setTime({});

		let existCreate = curNodeList.value.find(item => item.id === 'sm-drawer-demo-card-04');
		existCreate && curNodeList.value.pop();

		forms.forEach(form => {
			form.value.resetFields();
		});
	};

	defineExpose({ initForm, getInfo });
</script>
